<template>
  <div class="page">
    <el-container>
      <el-main>
        <el-table
          :data="courseGrid"
          border
          stripe
          style="width: 100%"
          :cell-style="{ padding: '8px' }"
        >
          <!-- 导入课表列 -->
          <el-table-column label="导入课表" width="150" align="center">
            <template #header>
              <el-upload
                action=""
                :auto-upload="false"
                :on-change="importSchedule"
                accept=".xlsx,.xls"
              >
                <el-button type="primary" size="small"><el-icon><upload/></el-icon>导入课表</el-button>
              </el-upload>
            </template>
            <template #default="{ row }">
              {{ row.time }}
            </template>
          </el-table-column>
          <!-- 周一到周五列 -->
          <el-table-column
            v-for="(day, index) in weekDays"
            :key="index"
            :label="day.week"
            :prop="`day${index}`"
            align="center"
            :formatter="formatCourse"
          >
            <template #default="{ row }">
              <el-tooltip
                v-if="row[`day${index}`]"
                :content="getCourseWeeks(row[`day${index}`])"
                placement="top"
              >
                <div class="course-info" :style="{ backgroundColor: row[`day${index}`].bgColor }">
                  <span class="course-name">{{ row[`day${index}`].name }}</span>
                  <span class="course-room">{{ row[`day${index}`].room }}</span>
                  <span class="course-teacher">{{ row[`day${index}`].teacher }}</span>
                </div>
              </el-tooltip>
            </template>
          </el-table-column>
        </el-table>
      </el-main>
    </el-container>
  </div>
</template>

<script>
import * as XLSX from 'xlsx';
import {Upload} from "@element-plus/icons-vue";

function getPastelColor() {
  const baseColor = 255;
  const variation = 66;
  const r = baseColor - Math.floor(Math.random() * variation);
  const g = baseColor - Math.floor(Math.random() * variation);
  const b = baseColor - Math.floor(Math.random() * variation);
  return `rgb(${r}, ${g}, ${b})`;
}

export default {
  components: {Upload},
  data() {
    return {
      weekDays: [
        { week: '周一', index: 0 },
        { week: '周二', index: 1 },
        { week: '周三', index: 2 },
        { week: '周四', index: 3 },
        { week: '周五', index: 4 },
      ],
      timeSlots: [
        { section: 1, time: '09:00-10:20' },
        { section: 2, time: '10:40-12:00' },
        { section: 3, time: '12:30-13:50' },
        { section: 4, time: '14:00-15:20' },
        { section: 5, time: '15:30-16:50' },
        { section: 6, time: '17:00-18:20' },
        { section: 7, time: '19:00-20:20' },
        { section: 8, time: '20:30-21:50' },
      ],
      courses: [],
      courseGrid: [],
    };
  },

  methods: {
    processCoursesData() {
      const grid = Array(8).fill(null).map(() => Array(5).fill(null));
      this.courses.forEach((course) => {
        if (
          course.section >= 1 &&
          course.section <= 8 &&
          course.day >= 0 &&
          course.day <= 4
        ) {
          if (!course.bgColor) {
            course.bgColor = getPastelColor();
          }
          grid[course.section - 1][course.day] = course;
        }
      });
      this.courseGrid = grid.map((row, index) => {
        const rowData = { time: this.timeSlots[index].time };
        this.weekDays.forEach((day, dayIndex) => {
          rowData[`day${dayIndex}`] = row[dayIndex];
        });
        return rowData;
      });
    },

    importSchedule(file) {
      const reader = new FileReader();
      reader.onload = (e) => {
        const data = e.target.result;
        const workbook = XLSX.read(data, { type: 'binary' });
        const firstSheetName = workbook.SheetNames[0];
        const worksheet = workbook.Sheets[firstSheetName];
        const jsonData = XLSX.utils.sheet_to_json(worksheet);
        const weekMap = {
          周一: 0,
          周二: 1,
          周三: 2,
          周四: 3,
          周五: 4,
        };
        const courses = jsonData
          .map((item) => {
            const section = Number(item['节次']);
            const day = weekMap[item['星期']];
            const weeks = item['周数'].split(' ').map((week) => Number(week));
            if (isNaN(section) || day === undefined) {
              return null;
            }
            return {
              name: (item['课程名称'] || '').trim(),
              code: (item['课程代码'] || '').trim(),
              teacher: (item['教师'] || '').trim(),
              room: (item['教室'] || '').trim(),
              day: day,
              section: section,
              weeks: weeks,
              bgColor: getPastelColor(),
            };
          })
          .filter((course) => course !== null);
        if (courses.length > 0) {
          this.courses = courses;
          this.processCoursesData();
          localStorage.setItem('courses', JSON.stringify(courses));
          this.$message.success('导入成功');
        } else {
          this.$message.warning('未找到有效数据');
        }
      };
      reader.readAsBinaryString(file.raw);
    },

    formatCourse(row, column, cellValue) {
      if (cellValue) {
        return `${cellValue.name}\n${cellValue.room}\n${cellValue.teacher}`;
      }
      return '';
    },

    getCourseWeeks(course) {
      return `上课周数: ${course.weeks.join(', ')}`;
    },
  },

  mounted() {
    const storedCourses = localStorage.getItem('courses');
    if (storedCourses) {
      this.courses = JSON.parse(storedCourses);
      this.processCoursesData();
    }
  },
};
</script>

<style lang="scss">
.page {
  //padding: 20px;
  background-color: #f5f7fa;
  min-height: 100vh;
}

.el-main {
  //padding: 20px;
  --el-main-padding: 0;

}

.el-table {
  margin-top: 20px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.course-info {
  padding: 10px;
  border-radius: 4px;
  text-align: center;
  cursor: pointer;
  transition: background-color 0.3s;
}

.course-info:hover {
  opacity: 0.9;
}

.course-name {
  font-weight: bold;
  display: block;
}

.course-room,
.course-teacher {
  font-size: 12px;
  color: #666;
  display: block;
}
</style>
